import { encrypt, decrypt } from 'crypto-js/aes'
import { parse } from 'crypto-js/enc-utf8'
import pkcs7 from 'crypto-js/pad-pkcs7'
import CFB from 'crypto-js/mode-cfb'
import UTF8 from 'crypto-js/enc-utf8'

// 注意 key 和 iv 至少都需要 16 位
const AES_KEY = 'TQn6yUj2g8S8FiLr' // 秘钥
const AES_IV = 'Ir/Wrb8/Vz66CKh4' // 初始化向量

export class AesEncryption {
  private key
  private iv

  constructor(key = AES_KEY, iv = AES_IV) {
    this.key = parse(key)
    this.iv = parse(iv)
  }

  get getOptions() {
    return {
      mode: CFB,
      padding: pkcs7,
      iv: this.iv
    }
  }

  /**
   * @description 加密
   * 浏览器中会将+号转义 先encodeURIComponent  解密的时候再decodeURIComponent
   * @param {string} text - 明文
   * @returns {string} - 密文
   */
  encryptByAES(text: string): string {
    const decodedString = encrypt(text, this.key, this.getOptions).toString()
    return encodeURIComponent(decodedString)
  }

  /**
   * @description 解密
   * @param {string} text - 密文
   * @returns {string} - 明文
   */
  decryptByAES(text: string): string {
    const bytes = decrypt(text, this.key, this.getOptions)
    return bytes.toString(UTF8)
  }
}
